<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/

// Define a destination
include("../services/config/connection.php");
include("../services/scripts.php");
$vehicle_id  = 0;


$errors = array();
$ids = array();

function file_extension($filename)
{
	return end(explode(".", $filename));
}
if (!empty($_FILES)) {
	$file_temp = $_FILES['Filedata']['tmp_name'];
	//$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
	//$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
	
	// Validate the file type
	$fileTypes = array('jpg','jpeg','gif','png','PNG','JPG','JPEG','GIF','PDF','pdf'); // File extensions
	$fileParts = pathinfo($_FILES['Filedata']['name']);
	
	if (in_array($fileParts['extension'],$fileTypes)) {
		$db_path_image = "services/upload_image/";
		$db_path_pdf= "services/upload_pdf/";
		
		$file_path_image = "../".$db_path_image;
		$file_path_pdf = "../".$db_path_pdf;
		if (file_extension($_FILES['Filedata']['name']) == "pdf")
		{
			$new_file_name = uniqid("auto").".pdf";
			$filestatus = move_uploaded_file($file_temp,$file_path_pdf.$new_file_name);
			if(!file_exists($file_path_pdf.$_FILES['Filedata']['name'])){
				if(!$filestatus){
					 $success = "false";
					 array_push($errors,"Upload failed. Please try again.");
					
				}else {
					$success = "true";
				}
				
				if(isset($_REQUEST['id'])){
					$vehicle_id = $_REQUEST['id'];
				}else{
					$vehicle_id = 0;
				}
				//create_thumbnail($file_path_image."pdf/pdf.png",$file_path_pdf."thump_pdf.jpg",50,40);
				$db_info = inserinto_database($vehicle_id, $db_path_pdf.$new_file_name, $db_path_pdf."thump_pdf.jpg",$db_path_pdf."thump_pdf.jpg");
echo  $db_info;
				
			}
			else {
				$success = "false";
				array_push($errors,"File already exists on server.");
			}
		}
		else
		{
			$new_file_name = uniqid("auto").".jpg";
			$filestatus = move_uploaded_file($file_temp,$file_path_image.$new_file_name);
			if(!file_exists($file_path_image.$_FILES['Filedata']['name'])) {
				if(!$filestatus) {
					 $success = "false";
					 array_push($errors,"Upload failed. Please try again.");
				} else {
					$success = "true";
				}				
				//$resizeObj = new resize($file_path_image.$new_file_name);
				// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
				//$resizeObj -> resizeImage(600, 500, 'crop');
				// *** 3) Save image
				//$resizeObj -> saveImage($file_path_image."crop/crop_".$new_file_name, 100);
				//unset($resizeObj);
				create_thumbnail($file_path_image.$new_file_name,$file_path_image."crop/crop_".$new_file_name,600,500);
				create_thumbnail($file_path_image.$new_file_name,$file_path_image."thumps/thump_".$new_file_name,50,40);
				if(isset($_REQUEST['id'])){
					$vehicle_id = $_REQUEST['id'];
				}else{
					$vehicle_id = 0;
				}
				
				$db_info = inserinto_database($vehicle_id, $db_path_image.$new_file_name, $db_path_image."thumps/thump_".$new_file_name, $db_path_image."crop/crop_".$new_file_name);
				echo  $db_info;
			} else {
				$success = "false";
				array_push($errors,"File already exists on server.");
			}
		}
		
	} else {
		echo 'Invalid file type.';
	}
}

function inserinto_database($vid, $filestr, $thumpstr, $cropstr)
	{
		$lastResult;
$myDate = date('Y-m-d H:i:s');
		
		$my_insert = "INSERT INTO vehicle_image (  `image_url` , `vehicle_id`, `thump_url`, `crop_url`  ) VALUES ('".$filestr. "',".$vid.",'" .$thumpstr. "','".$cropstr."')";  
		$my_insert = mysql_query($my_insert) or die("Query ERROR");
		$result_sel = mysql_insert_id();
		$lastResult->imageUrl = $filestr;
		$lastResult->thumpUrl = $thumpstr;
		$lastResult->cropUrl = $cropstr;
		$lastResult->imageID = $result_sel;
    	$lastResult->vehID = $vid;
		$result =  return_1w_result($lastResult, $result_sel);
		/* Update date new implementaion*/
$myDate = date('Y-m-d H:i:s');
	    VehicleDAOImpl::getInstance()->updateVehicleFieldByID($vid, "update_date", "'".$myDate."'", "current_action", "Reply from seller", "");
return $result;

	}
	
	function create_thumbnail($infile,$outfile,$maxw,$maxh,$stretch = FALSE) 
	{
	  clearstatcache();
	  if (!is_file($infile)) {
	    trigger_error("Cannot open file: $infile",E_USER_WARNING);
	    return FALSE;
	  }
	  if (is_file($outfile)) {
	      trigger_error("Output file already exists: $outfile",E_USER_WARNING);
	    return FALSE;
	  }
	 
	  $functions = array(
	    'image/png' => 'ImageCreateFromPng',
	    'image/jpeg' => 'ImageCreateFromJpeg',
	  );
	 
	  // Add GIF support if GD was compiled with it
	  if (function_exists('ImageCreateFromGif')) { $functions['image/gif'] = 'ImageCreateFromGif'; }
	 
	  $size = getimagesize($infile);
	 
	  // Check if mime type is listed above
	  if (!$function = $functions[$size['mime']]) {
	      trigger_error("MIME Type unsupported: {$size['mime']}",E_USER_WARNING);
	    return FALSE;
	  }
	 
	  // Open source image
	  if (!$source_img = $function($infile)) {
	      trigger_error("Unable to open source file: $infile",E_USER_WARNING);
	    return FALSE;
	  }
	 
	  $save_function = "image" . strtolower(substr(strrchr($size['mime'],'/'),1));
	 
	  // Scale dimensions
	  list($neww,$newh) = scale_dimensions($size[0],$size[1],$maxw,$maxh,$stretch);
	 
	  if ($size['mime'] == 'image/png') {
	    // Check if this PNG image is indexed
	    $temp_img = imagecreatefrompng($infile);
	    if (imagecolorstotal($temp_img) != 0) {
	      // This is an indexed PNG
	      $indexed_png = TRUE;
	    } else {
	      $indexed_png = FALSE;
	    }
	    imagedestroy($temp_img);
	  }
	 
	  // Create new image resource
	  if ($size['mime'] == 'image/gif' || ($size['mime'] == 'image/png' && $indexed_png)) {
	    // Create indexed 
	    $new_img = imagecreate($neww,$newh);
	    // Copy the palette
	    imagepalettecopy($new_img,$source_img);
	 
	    $color_transparent = imagecolortransparent($source_img);
	    if ($color_transparent >= 0) {
	      // Copy transparency
	      imagefill($new_img,0,0,$color_transparent);
	      imagecolortransparent($new_img, $color_transparent);
	    }
	  } else {
	    $new_img = imagecreatetruecolor($neww,$newh);
	  }
	 
	  // Copy and resize image
	  imagecopyresampled($new_img,$source_img,0,0,0,0,$neww,$newh,$size[0],$size[1]);
	 
	  // Save output file
	  if ($save_function == 'imagejpeg') {
	      // Change the JPEG quality here
	      if (!$save_function($new_img,$outfile,75)) {
	          trigger_error("Unable to save output image",E_USER_WARNING);
	          return FALSE;
	      }
	  } else {
	      if (!$save_function($new_img,$outfile)) {
	          trigger_error("Unable to save output image",E_USER_WARNING);
	          return FALSE;
	      }
	  }
	 
	  // Cleanup
	  imagedestroy($source_img);
	  imagedestroy($new_img);
	 
	  return TRUE;
	}
	// Scales dimensions
	function scale_dimensions($w,$h,$maxw,$maxh,$stretch = FALSE) {
	    if (!$maxw && $maxh) {
	      // Width is unlimited, scale by width
	      $newh = $maxh;
	      if ($h < $maxh && !$stretch) { $newh = $h; }
	      else { $newh = $maxh; }
	      $neww = ($w * $newh / $h);
	    } elseif (!$maxh && $maxw) {
	      // Scale by height
	      if ($w < $maxw && !$stretch) { $neww = $w; }
	      else { $neww = $maxw; }
	      $newh = ($h * $neww / $w);
	    } elseif (!$maxw && !$maxh) {
	      return array($w,$h);
	    } else {
	      if ($w / $maxw > $h / $maxh) {
	        // Scale by height
	        if ($w < $maxw && !$stretch) { $neww = $w; }
	        else { $neww = $maxw; }
	        $newh = ($h * $neww / $w);
	      } elseif ($w / $maxw <= $h / $maxh) {
	        // Scale by width
	        if ($h < $maxh && !$stretch) { $newh = $h; }
	        else { $newh = $maxh; }
	        $neww = ($w * $newh / $h);
	      }
	    }
	    return array(round($neww),round($newh));
	}
	
	function return_1w_result($info, $imageId)
	{
		
		$query_data = "SELECT * FROM vehicle_image WHERE image_id IN(".$imageId.")" ;
        $result_data = mysql_query($query_data) or die("Query ERROR5");      
		$result =    "<results>";		
		while ($row =  mysql_fetch_object($result_data))
		{
			$result .= "<result>";
			$result .= "<imageid>".$row->image_id."</imageid>";
			$result .= "<imageUrl>".$row->image_url."</imageUrl>";
			$result .= "<thumpUrl>".$row->thump_url."</thumpUrl>";
			$result .= "<cropUrl>".$row->crop_url."</cropUrl>";
			$result .= "</result>";
		}
		$result .=    "</results>";
		return $result;
	}
	
	function return_2w_result()
	{
		$query_data = "SELECT `thump_url` FROM vehicle_image WHERE vehicle_id='".$vehicle_id."'" ;
        $result_data = mysql_query($query_data) or die("Query ERROR5");
      	$result = '';
		while ($row =  mysql_fetch_object($result_data))
		{
			$result .= '<div><div  style="background-color:white; border:#c2c2c2 solid 1px; margin:5px; width:60px; height:50px; text-align: center; float:left;border-width:1px;border-style:solid;border-color:white;   line-height: 35px; font-size: 1em;"><img style=" margin-top: 5px " src=../../'. $row->thump_url .'></div></div>';
		}
		echo $result;
	}
?>